from django.shortcuts import render, redirect, reverse, HttpResponse
from django.utils.decorators import method_decorator
from django.http import JsonResponse
from django.views import View
import hashlib
import time
from app01 import models
from app01.status_code import StatusCode


def get_md5_str(str1):
	"""加盐的md5加密"""
	md5_obj = hashlib.md5("锄禾日当午".encode("utf-8"))
	md5_obj.update(str1.encode("utf-8"))
	return md5_obj.hexdigest()


def user_auth(func):
	'''装饰器函数，用户登录后，才可以进入用户列表页面'''

	def inner(request, *args, **kwargs):
		user = request.session.get('user')
		if user:
			return func(request, *args, **kwargs)
		else:
			return redirect(reverse('app01:login'))

	return inner


@method_decorator(user_auth, name='dispatch')
class Login(View):
	'''用户登录'''

	def get(self, request):
		return render(request, 'login.html')

	def post(self, request):
		username = request.POST.get('username')
		pwd = request.POST.get('password')
		sel = models.UserInfo.objects.filter(username=username, password=get_md5_str(pwd))
		if sel:
			# 登录成功
			request.session['user'] = username
			return redirect(reverse('app01:user'))
		else:
			# 登录失败
			return render(request, 'login.html', StatusCode(error='用户名或密码错误').code_dict())


# 判断用户是否已登录，加在类上[dispatch方法]
@method_decorator(user_auth, name='dispatch')
class UserList(View):
	'''用户列表'''

	def get(self, request):
		user_list = models.UserInfo.objects.all()
		return render(request, 'user_list.html', locals())


@method_decorator(user_auth, name='dispatch')
class AddUser(View):
	'''添加用户'''

	def get(self, request):
		# 检查用户是否已存在
		if request.is_ajax():
			cmd = request.GET.get('cmd')
			if cmd == 'checkUserExist':
				username = request.GET.get('username')
				if models.UserInfo.objects.filter(username=username):
					res_dict = {"user_exist": 1}
				else:
					res_dict = {"user_exist": 0}
				return JsonResponse(res_dict)

		return render(request, 'add_user.html', locals())

	def post(self, request):
		username = request.POST.get('username')
		# 判断用户名是否已存在
		if models.UserInfo.objects.filter(username=username):
			return render(request, 'add_user.html', StatusCode(error='用户名已存在').code_dict())

		pwd = request.POST.get('password')
		gender = request.POST.get('gender')
		age = request.POST.get('age')
		email = request.POST.get('email')
		phone = request.POST.get('phone')
		userType = request.POST.get('userType')
		md5_pwd = get_md5_str(pwd)
		age = 0 if (not age) else age
		models.UserInfo.objects.create(
			username=username,
			password=md5_pwd,
			gender=gender,
			age=age,
			email=email,
			phone=phone,
			userType=userType,
		)
		return redirect(reverse('app01:user'))


@method_decorator(user_auth, name='dispatch')
class DelUser(View):
	'''删除用户'''

	def get(self, request, pk):
		models.UserInfo.objects.filter(pk=pk).delete()
		return redirect(reverse('app01:user'))


@method_decorator(user_auth, name='dispatch')
class EditUser(View):
	'''编辑用户'''

	def get(self, request, pk):
		user_obj = models.UserInfo.objects.filter(pk=pk).first()
		return render(request, 'edit_user.html', locals())

	def post(self, request, pk):
		new_pwd = request.POST.get('password')
		new_gender = request.POST.get('gender')
		new_age = request.POST.get('age')
		new_email = request.POST.get('email')
		new_phone = request.POST.get('phone')
		new_userType = request.POST.get('userType')
		new_age = 0 if not new_age else new_age

		# 密码不为空时，修改密码
		if new_pwd:
			models.UserInfo.objects.filter(pk=pk).update(
				password=get_md5_str(new_pwd),
				gender=new_gender,
				age=new_age,
				email=new_email,
				phone=new_phone,
				userType=new_userType
			)
		else:
			models.UserInfo.objects.filter(pk=pk).update(
				gender=new_gender,
				age=new_age,
				email=new_email,
				phone=new_phone,
				userType=new_userType
			)
		return redirect(reverse('app01:user'))


@method_decorator(user_auth, name='dispatch')
class Logout(View):
	'''退出'''

	def get(self, request):
		request.sessio.flush
		return redirect(reverse('app01:login'))


@method_decorator(user_auth, name='dispatch')
class AddHost(View):
	'''添加主机'''

	def get(self, request):
		service_line_lst = models.ServiceLine.objects.all()
		# 检查主机是否已存在
		if request.is_ajax():
			cmd = request.GET.get('cmd')
			print('cmd: ', cmd)
			if cmd == 'checkHostExist':
				hostname = request.GET.get('hostname')
				if models.Host.objects.filter(hostname=hostname):
					res_dict = {"exist": 1}
				else:
					res_dict = {"exist": 0}
				return JsonResponse(res_dict)

		return render(request, 'add_host.html', locals())

	def post(self, request):
		hostname = request.POST.get('hostname')
		# 判断主机名是否已存在
		if models.Host.objects.filter(hostname=hostname):
			return render(request, 'add_host.html', StatusCode(error='主机名已存在').code_dict())

		hostIp = request.POST.get('hostIp')
		pwd = request.POST.get('password')
		service_line_id = request.POST.get('service_line_id')
		models.Host.objects.create(
			hostname=hostname,
			hostIp=hostIp,
			password=get_md5_str(pwd),
			service_line_id=service_line_id
		)
		return redirect(reverse('app01:host'))


@method_decorator(user_auth, name='dispatch')
class HostList(View):
	'''主机列表'''

	def get(self, request):
		host_list = models.Host.objects.all()
		return render(request, 'host_list.html', locals())


@method_decorator(user_auth, name='dispatch')
class DelHost(View):
	'''删除用户'''

	def get(self, request, pk):
		models.Host.objects.filter(pk=pk).delete()
		return redirect(reverse('app01:host'))


@method_decorator(user_auth, name='dispatch')
class EditHost(View):
	'''编辑主机'''

	def get(self, request, pk):
		service_line_lst = models.ServiceLine.objects.all()
		host_obj = models.Host.objects.filter(pk=pk).first()
		return render(request, 'edit_host.html', locals())

	def post(self, request, pk):
		hostname = request.POST.get('hostname')
		if models.Host.objects.exclude(pk=pk).filter(hostname=hostname):
			return render(request, 'edit_host.html', StatusCode(error='主机名已存在').code_dict())

		new_pwd = request.POST.get('password')
		hostIp = request.POST.get('edit_hostIp')
		service_line_id = request.POST.get('service_line_id')

		# 密码不为空时，修改密码
		if new_pwd:
			models.Host.objects.filter(pk=pk).update(
				password=get_md5_str(new_pwd),
				hostIp=hostIp,
				service_line_id=service_line_id
			)
		else:
			models.Host.objects.filter(pk=pk).update(
				hostIp=hostIp,
				service_line_id=service_line_id
			)
		return redirect(reverse('app01:host'))


@method_decorator(user_auth, name='dispatch')
class AddServiceLine(View):
	'''添加业务线'''

	def get(self, request):
		# 检查业务线是否已存在
		if request.is_ajax():
			cmd = request.GET.get('cmd')
			if cmd == 'checkServiceLineExist':
				serviceLineName = request.GET.get('serviceLineName')
				if models.ServiceLine.objects.filter(name=serviceLineName):
					res_dict = {"exist": 1}
				else:
					res_dict = {"exist": 0}
				return JsonResponse(res_dict)

		return render(request, 'add_serviceLine.html', locals())

	def post(self, request):
		serviceLineName = request.POST.get('serviceLineName')
		# 判断业务线是否已存在
		if models.ServiceLine.objects.filter(name=serviceLineName):
			return render(request, 'add_serviceLine.html', StatusCode(error='业务线已存在').code_dict())

		models.ServiceLine.objects.create(
			name=serviceLineName
		)
		return redirect(reverse('app01:serviceLine'))


@method_decorator(user_auth, name='dispatch')
class ServiceLineList(View):
	'''业务线列表'''

	def get(self, request):
		serviceLine_list = models.ServiceLine.objects.all()
		return render(request, 'serviceLine_list.html', locals())


@method_decorator(user_auth, name='dispatch')
class DelServiceLine(View):
	'''删除业务线'''

	def get(self, request, pk):
		models.ServiceLine.objects.filter(pk=pk).delete()
		return redirect(reverse('app01:serviceLine'))


@method_decorator(user_auth, name='dispatch')
class EditServiceLine(View):
	'''编辑业务线'''

	def get(self, request, pk):
		serviceLine_obj = models.ServiceLine.objects.filter(pk=pk).first()
		return render(request, 'edit_serviceLine.html', locals())

	def post(self, request, pk):
		serviceLineName = request.POST.get('editServiceLineName')
		if models.ServiceLine.objects.exclude(pk=pk).filter(name=serviceLineName):
			return render(request, 'edit_serviceLine.html', StatusCode(error='业务线已存在').code_dict())

		models.ServiceLine.objects.filter(pk=pk).update(
			name=serviceLineName
		)
		return redirect(reverse('app01:serviceLine'))


# 查看主机信息
@method_decorator(user_auth, name='dispatch')
class ShowHost(View):
	def get(self, request, pk):
		ser_obj = models.ServiceLine.objects.filter(pk=pk).first()
		host_list = ser_obj.hosts.all()
		return render(request, 'host_list.html', locals())


# 用户和业务线关系
@method_decorator(user_auth, name='dispatch')
class ServiceLineUser(View):
	def get(self, request):
		ser_all = models.ServiceLine.objects.all()
		ret_dict = []
		for ser_obj in ser_all:
			user_list = ser_obj.userinfos.values('id', 'username')
			if user_list:
				ser_dict = {}
				ser_dict['ser_pk'] = ser_obj.pk
				ser_dict['ser_name'] = ser_obj.name
				ser_dict['user_dict'] = user_list
				ret_dict.append(ser_dict)
		return render(request, 'serviceLine_user.html', locals())


# 删除业务线和用户关系
@method_decorator(user_auth, name='dispatch')
class DelServiceLineUser(View):
	def get(self, request, ser_pk, user_pk):
		ser_obj = models.ServiceLine.objects.filter(pk=ser_pk).first()
		ser_obj.userinfos.remove(user_pk)
		return redirect('app01:serviceLine_user')


# 编辑业务线和用户关系
@method_decorator(user_auth, name='dispatch')
class EditServiceLineUser(View):
	def get(self, request, ser_pk, user_pk):
		ser_obj = models.ServiceLine.objects.filter(pk=ser_pk).first()
		username = ser_obj.userinfos.filter(pk=user_pk).values('username')
		user_list = models.UserInfo.objects.values('id', 'username')
		user_pk = int(user_pk)
		return render(request, 'edit_serviceLine_user.html', locals())

	def post(self, request, ser_pk, user_pk):
		editServiceLineId = request.POST.get('editServiceLineId')
		user_id = request.POST.get('user_id')
		ser_obj = models.ServiceLine.objects.filter(pk=ser_pk).first()
		if user_id == user_pk:
			return redirect('app01:serviceLine_user')
		else:
			if ser_obj.userinfos.filter(pk=user_id):
				error = '业务线和用户关系已存在'
				username = ser_obj.userinfos.filter(pk=user_pk).values('username')
				user_list = models.UserInfo.objects.values('id', 'username')
				user_pk = int(user_pk)
				return render(request, 'edit_serviceLine_user.html', locals())
			else:
				ser_obj.userinfos.remove(user_pk)
				ser_obj.userinfos.add(user_id)
				return redirect('app01:serviceLine_user')


# 添加业务线和用户关系
@method_decorator(user_auth, name='dispatch')
class AddServiceLineUser(View):
	def get(self, request):
		user_list = models.UserInfo.objects.values('pk', 'username')
		ser_list = models.ServiceLine.objects.values('pk', 'name')
		return render(request, 'add_serviceLine_user.html', locals())

	def post(self, request):
		service_line_id = request.POST.get('service_line_id')
		user_id = request.POST.get('user_id')
		ser_obj = models.ServiceLine.objects.filter(pk=service_line_id).first()
		if ser_obj.userinfos.filter(pk=user_id):
			user_list = models.UserInfo.objects.values('pk', 'username')
			ser_list = models.ServiceLine.objects.values('pk', 'name')
			error = '业务线和用户关系已存在'
			return render(request, 'add_serviceLine_user.html', locals())
		else:
			ser_obj.userinfos.add(user_id)
		return redirect('app01:serviceLine_user')


# 显示业务和用户关系信息
@method_decorator(user_auth, name='dispatch')
class ShowUser(View):
	def get(self, request, pk):
		ser_obj = models.ServiceLine.objects.filter(pk=pk).first()
		user_list = ser_obj.userinfos.all()
		return render(request, 'user_list.html', locals())


@method_decorator(user_auth, name='dispatch')
class ShowServiceLine(View):
	def get(self, request, pk):
		user_obj = models.UserInfo.objects.filter(pk=pk).first()
		serviceLine_list = user_obj.serviceLines.all()
		return render(request, 'serviceLine_list.html', locals())



from django.db.models import F,Q
class Book(View):
	'''练习题'''

	def get(self, request):
		# 1、 查询老男孩出版社出版过的价格大于200的书籍
		ret = models.Book.objects.filter(pub__publisher_name__contains='老男孩出版社', book_price__gt=200).values('book_name')
		ret = models.Book.objects.filter(Q(pub__publisher_name='老男孩出版社'), Q(book_price__gt=200)).values()
		# 2、 查询所有以py开头的书籍名称
		# ret = models.Book.objects.filter(book_name__istartswith='py').values('book_name')
		# 3、查询价格为50, 100或者150的所有书籍名称及其出版社名称
		# ret = models.Book.objects.filter(book_price__in=[50, 100, 150]).values('book_name', 'pub__publisher_name')
		# 4、查询价格在100到200之间的所有书籍名称及其价格
		# ret = models.Book.objects.filter(book_price__range=[100, 200]).values('book_name', 'book_price')
		# 5.查询所有人民出版社出版的书籍的价格（从高到低排序，去重）
		# ret = models.Book.objects.filter(pub__publisher_name__contains='人民出版社').values(
		# 	'book_price').distinct().order_by('-book_price')
		# 6.查询价格大于200的书籍的个数
		# ret = models.Book.objects.filter(book_price__gt=200).values().count()
		# 7.查询价格不等于100的所有书籍
		# ret = models.Book.objects.exclude(book_price=100).values()
		return HttpResponse(ret)
